package cn.walls1717.wallsmall.member.interceptor;

import cn.walls1717.wallsmall.common.pojo.vo.MemberRespVO;
import cn.walls1717.wallsmall.member.util.UserHandler;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static cn.walls1717.wallsmall.common.constant.auth.AuthServerConstant.LOGIN_USER;

/**
 * 用户登录拦截器
 *
 * @author walls1717
 * @since 2022/11/18 11:14
 **/
public class LoginUserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response,
        @NotNull Object handler) throws Exception {

        boolean match = new AntPathMatcher().match("/member/**", request.getRequestURI());
        if (match) {
            return true;
        }
        MemberRespVO attribute = (MemberRespVO)request.getSession().getAttribute(LOGIN_USER);
        // 用户没有登录，跳转登录页面。
        if (attribute == null) {
            request.getSession().setAttribute("msg", "请先登录");
            response.sendRedirect("http://auth.wallsmall.com/login.html");
            return false;
        }
        UserHandler.set(attribute);
        return true;
    }
}
